//
//  YDASearchController.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/27.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "YDASearchController.h"
#import "YDASearchModel.h"
#import "YDASearchView.h"
#import "YDASearchResultCell.h"
#import "YDASearchHeaderView.h"
#import "YDASearchHistoryCell.h"

#import "YDALoginController.h"

#pragma 跳转到点买
#import "YDVerticalStockBuyController.h"


@interface YDASearchController ()<SYASearchViewDelegate , UITableViewDelegate , UITableViewDataSource , SYASearchResultCellDelegate , SYASearchHistoryCellDelegate>
//搜索框界面
@property (nonatomic , weak) YDASearchView *searchView;
//tableView
@property (nonatomic , weak) UITableView *tableView;

//数据源数组
//搜索结果模型数组
@property (nonatomic , strong) NSMutableArray *resultModelArray;
//搜索历史记录数据
@property (nonatomic , strong) NSMutableArray *historyArray;

@end

@implementation YDASearchController

-(NSMutableArray *)resultModelArray
{
    if (_resultModelArray == nil) {
        _resultModelArray = [NSMutableArray array];
    }
    return _resultModelArray;
}
-(NSMutableArray *)historyArray
{
    if (_historyArray == nil) {
        _historyArray = [NSMutableArray array];
    }
    return _historyArray;
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    //    self.extendedLayoutIncludesOpaqueBars = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"支点找股";
    self.view.backgroundColor = [UIColor whiteColor];
    //处理历史搜索数据
    [self resloveHistorySearchData];
    
    [self setUpNavButton];
    [self searchView];
    [self tableView];
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.searchView searhBarBeginFirstResgister];
    [self.view becomeFirstResponder];
    //开启搜索
    if (self.searchString.length) {
        DDLog(@"搜索界面 = %@",self.searchString)
        [self.searchView searchWithSearchString:self.searchString];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.searchView searhBarEndEditor];
    [self.view endEditing:YES];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.searchView searhBarEndEditor];
    [self.view endEditing:YES];
}
/***********设置导航栏按钮*************/
-(void)setUpNavButton
{
    if (self.searchStyle == Search_Present) {
        //present进来的左上角按钮为关闭
        UIBarButtonItem *leftItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"rightClose"] hightImage:[UIImage imageNamed:@"rightClose"] addTarget:self action:@selector(leftItemButtonClick:)];
        self.navigationItem.leftBarButtonItem = leftItemBtn;
        
    }
}

- (void)leftItemButtonClick:(UIButton *)button
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}
/***********搜搜框*************/
-(YDASearchView *)searchView
{
    if (_searchView == nil) {
        //        CGFloat navH = self.navigationController.navigationBar.height;
        
        YDASearchView *searchView = [[YDASearchView alloc] init];
        [self.view addSubview:searchView];
        CGRect searchFrame;
        if (isPhoneX) {
            searchFrame = CGRectMake(0, 0, LKScreenW, rateX812(50));
        }else{
            searchFrame = CGRectMake(0, 0, LKScreenW, rate750(50));
        }
        
        searchView.frame = searchFrame;
        
        searchView.delegate = self;
        _searchView = searchView;
    }
    return _searchView;
}
#pragma SYASearchViewDelegate
-(void)aSearchView:(YDASearchView *)searchView searchString:(NSString *)string isStoreHistory:(BOOL)isHistory
{
    if (string.length == 0) {
        [self.resultModelArray removeAllObjects];
        [self.tableView reloadData];
        return;
    }else{
        [self beginSearchWithString:string];
    }
}

/*************开始搜索***************/
-(void)beginSearchWithString:(NSString *)codeString
{
    
    NSString *encodeURL = [codeString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *url = [NSString stringWithFormat:@"/stock/selectStock?keyword=%@",encodeURL];
    NSString *urlString = [NSString stringWithFormat:@"%@%@",baseUrlHttp, url];
    NSString *token = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *manager = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [manager sessionWithToken:token RequestWithDictionary:nil andURLString:urlString andBody:nil WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"resultDict = %@",resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.resultModelArray removeAllObjects];//清空
            //重新装载新数据
            self.resultModelArray = [YDASearchModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self.tableView reloadData];
        }else{
            
        }
    } failBlock:^(NSError *error) {
        DDLog(@"error = %@",error)
    }];
}

/*************添加tableView***************/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), LKScreenW, LKScreenH - CGRectGetMaxY(self.searchView.frame) - self.navigationController.navigationBar.height) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        _tableView = tableView;
    }
    return _tableView;
}

/**********UITableViewDelegate , UITableViewDataSource*********/
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.resultModelArray.count) {//搜索结果有数据,只显示搜索结果
        return 1;
    }else if (self.resultModelArray.count == 0 && self.historyArray.count){//搜索结果没数据，但是历史记录有数据，只显示历史记录
        return 1;
    }else{//都没有数据
        return 0;
    }
    
    //    return 2;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.resultModelArray.count) {//搜索结果有数据,只显示搜索结果
        return self.resultModelArray.count;
    }else if (self.resultModelArray.count == 0 && self.historyArray.count){//搜索结果没数据，但是历史记录有数据，只显示历史记录
        return 1;
    }else{//都没有数据
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.resultModelArray.count) {//搜索结果有数据,只显示搜索结果
        return isPhoneX ? rateX812(54) : rate750(54);
    }else if (self.resultModelArray.count == 0 && self.historyArray.count){//搜索结果没数据，但是历史记录有数据，只显示历史记录
        return [self getHistoryCellHeight];
    }else{//都没有数据
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(20) : rate750(20);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YDASearchHeaderView *headerView = [YDASearchHeaderView headerViewWithTableView:tableView];
    if (self.resultModelArray.count) {//搜索结果有数据,只显示搜索结果
        headerView.titleLabel.text = @"搜索结果:";
    }else if (self.resultModelArray.count == 0 && self.historyArray.count){//搜索结果没数据，但是历史记录有数据，只显示历史记录
        headerView.titleLabel.text = @"搜搜历史记录:";
    }else{//都没有数据
        return nil;
    }
    return headerView;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.resultModelArray.count) {//搜索结果有数据,只显示搜索结果
        YDASearchResultCell *cell = [YDASearchResultCell cellWithTableView:tableView];
        cell.delegate = self;
        
        YDASearchModel *model = self.resultModelArray[indexPath.row];
        cell.model = model;
        return cell;
    }else if (self.resultModelArray.count == 0 && self.historyArray.count){//搜索结果没数据，但是历史记录有数据，只显示历史记录
        YDASearchHistoryCell *hisCell = [YDASearchHistoryCell cellWithTableView:tableView];
        //将历史记录数据传递过去
        
        hisCell.array = [self.historyArray copy];
        hisCell.delegate = self;
        return hisCell;
    }else{//都没有数据
        return nil;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    if (self.resultModelArray.count) {
        [self storeHistorySearchWithIndexPath:indexPath];
        YDASearchModel *model = self.resultModelArray[indexPath.row];
        if (self.searchStyle == Search_Push) {
#pragma 跳转到详情
            YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
            vc.isNormal = NO;
            vc.isActivity = NO;
            vc.isPopToRootC = NO;
            vc.stockCode = model.code;
            vc.stockName = model.name;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
        else
        {
            //diss回去点买
            if (self.dissBack) {
                self.dissBack(model.name, model.code);
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            });
            
        }
    }
}

/****************SYASearchResultCellDelegate************/
-(void)aSearchResultCellClickButton:(YDASearchResultCell *)resultCell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:resultCell];
    
    
    YDASearchModel *model = self.resultModelArray[indexPath.row];
    if (model.favorite) {//删自选
        [self deleteOptionalStockWithStockId:indexPath];
    }else{//加自选
        
        [self addOptionalStockWithStockId:indexPath];
    }
}

/**************SYASearchHistoryCellDelegate***********/

-(void)sSearchHistoryCell:(YDASearchHistoryCell *)historyCell didClickButton:(NSInteger)buttonTag
{
    DDLog(@"%zd-----%@",buttonTag , self.historyArray[buttonTag])
    //获取搜索字符
    NSString *searchString = self.historyArray[buttonTag];
    
    [self.searchView searchWithSearchString:searchString];
}

/**************存储历史搜索记录***********/
-(void)storeHistorySearchWithIndexPath:(NSIndexPath *)indexPath
{
    YDASearchModel *model = self.resultModelArray[indexPath.row];
    
    NSString *string = model.name;
    
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:peizidbName];
    NSMutableArray *array;
    NSMutableArray *Marray;//改变数组
    if ([store isExistTableWithName:peiziSearchHistory]) {
        id obj = [store getObjectById:peiziSearchHistory fromTable:peiziSearchHistory];
        
        array = [obj mutableCopy];
        
        Marray = [NSMutableArray arrayWithArray:obj];
        
        for (NSString *obj in array) {
            
            if ([obj isEqualToString:string]) {
                
                [Marray removeObject:obj];
            }
        }
        [Marray insertObject:string atIndex:0];
        if (Marray.count > 20) {
            [Marray subarrayWithRange:NSMakeRange(0, 20)];
        }
    }else{
        [store createTableWithName:peiziSearchHistory];
        Marray = [NSMutableArray array];
        [Marray addObject:string];
        
    }
    [store putObject:Marray withId:peiziSearchHistory intoTable:peiziSearchHistory];
}
/**************读取历史搜索记录***********/
-(void)resloveHistorySearchData
{
    //从本地数据库中读取数据，放到历史搜索数组当中，限制数量20个，每次都是搜索成功之后，更新历史搜索数据
    //界面刷新显示的时候，当搜索结果数组有数据，显示搜索结果，不现实历史搜索数据，
    //当历史搜索数组有数据的时候，显示历史搜索数据，不现实搜索结果数据
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:peizidbName];
    NSMutableArray *array;
    
    if ([store isExistTableWithName:peiziSearchHistory]) {
        id obj = [store getObjectById:peiziSearchHistory fromTable:peiziSearchHistory];
        
        array = [obj mutableCopy];
        [self.historyArray addObjectsFromArray:array];
        
    }else{
        
        
    }
}
//获取历史搜搜cell的高度，这个高度为粗略计算的，
-(CGFloat)getHistoryCellHeight
{
    CGFloat iconH;//一个标签的高度
    CGFloat margin;
    if (isPhoneX) {
        iconH = rateX812(22);
        margin = rateX812(10);
    }else{
        iconH = rate750(22);
        margin = rate750(10);
    }
    
    if (self.historyArray.count == 0) {
        return 0.0f;
    }else{
        //获取行数
        NSInteger col = self.historyArray.count / 4;
        return col * iconH + iconH + (col + 2) * margin;
    }
}
//加自选
-(void)addOptionalStockWithStockId:(NSIndexPath *)indexPath
{
    
    if (![SYUserInformation sharedInstance].isLogin) {
        //没有登录直接弹登录页面
        [self presentLoginVC];
        return;
    }
    YDASearchModel *model = self.resultModelArray[indexPath.row];
    [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:model.code forKey:@"stockCode"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:AddOptionalStock WithSuccessBlock:^(NSDictionary *resultDict) {
                DDLog(@"收藏成功信息%@",resultDict);
                DDLog(@"message= %@",resultDict[@"message"]);
                DDLog(@"result= %@",resultDict[@"result"]);
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([resultDict[@"code"] integerValue] == 200) {//注册成功
            
            model.favorite = YES;
            [self.tableView reloadData];
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeSuccess text:@"成功添加到自选，请在自选中查看" isExistNav:YES];
            //@"已从自选中移除" : @"成功添加到自选，请在自选中查看";
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        DDLog(@"%@" , error)
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"添加自选出错，请稍后重试" isExistNav:YES];
    }];
    
}
//删自选
-(void)deleteOptionalStockWithStockId:(NSIndexPath *)indexPath
{
    YDASearchModel *model = self.resultModelArray[indexPath.row];
    //    NSString *IDs = [NSString stringWithFormat:@"%zd",model.Id];
    [[SYProgressHUD sharedInstance] showMBHudWithSting:@""];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:model.code forKey:@"stockCodes"];
    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:DeleteOptionalStock WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        //            DDLog(@"%@",resultDict)
        //            DDLog(@"%@",resultDict[@"message"])
        
        if ([resultDict[@"code"] integerValue] == 200) {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeSuccess text:@"已从自选中移除" isExistNav:YES];
            model.favorite = NO;
            [self.tableView reloadData];
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        DDLog(@"%@",error)
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"移除自选出错，请重试~" isExistNav:YES];
    }];
    
    
}
- (void)presentLoginVC
{
    YDALoginController *loginVC = [[YDALoginController alloc] init];
    loginVC.loginStyle = Login_Present;
    YDABaseNavigationController *baseNav = [[YDABaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:baseNav animated:YES completion:nil];
}






@end
